import { defineStore } from "pinia"
import { ref } from "vue"
import { getSimilarMatchesApi, getMatcheSignalApi } from "@/pages/xinhaozhi/apis/index"
import type * as Football from "@/pages/xinhaozhi/apis/type"
import { 
  toFixedFour, 
  generateHourlyNullSeries, 
  mergeDataWithNullSeries, 
  fillNullsWithPreviousValue, 
  getTimeRange, 
  generateCompanyChartData,
  type ChartData 
} from "./utils"

interface OddsData {
  oddsTime: string | null
  homeWin: number
  draw: number
  awayWin: number
  homeWinRate: string
  drawRate: string
  awayWinRate: string
  signalHome: number | null
  signalDraw: number | null
  signalAway: number | null
}

export const useSimilarMatchStore = defineStore("similarMatch", () => {
  // State
  const isLoadingSimilarMatches = ref(false)
  const isLoadingSimilarMatchSignals = ref(false)
  
  // 相似比赛相关状态
  const similarMatches = ref<Football.SimilarMatches[]>([])
  const similarMatchesPagination = ref<Football.PaginationInfo>({
    current_page: 1,
    page_size: 20,
    total: 0,
    total_pages: 0
  })
  const similarMatchesStatistics = ref<Football.MatchStatistics | null>(null)
  
  // 相似比赛详情相关状态
  const selectedSimilarMatch = ref<Football.SimilarMatches | null>(null)
  const similarMatch293Signals = ref<Football.Signal[]>([])
  const similarMatch18Signals = ref<Football.Signal[]>([])
  const similarMatchLeftTableData = ref<OddsData[]>([])
  const similarMatchRightTableData = ref<OddsData[]>([])
  const similarMatchLeftBottomChart293 = ref<ChartData>({ xData: [], seriesData: [] })
  const similarMatchLeftBottomChart18 = ref<ChartData>({ xData: [], seriesData: [] })
  const similarMatchRightCombinedChartHome = ref<ChartData>({ xData: [], seriesData: [] })
  const similarMatchRightCombinedChartDraw = ref<ChartData>({ xData: [], seriesData: [] })
  const similarMatchRightCombinedChartAway = ref<ChartData>({ xData: [], seriesData: [] })

  // 相似比赛详情相关状态 - 使用Map来存储每个比赛的独立数据
  const similarMatchDataMap = ref<Map<number, {
    signals293: Football.Signal[],
    signals18: Football.Signal[],
    leftTableData: OddsData[],
    rightTableData: OddsData[],
    leftBottomChart293: ChartData,
    leftBottomChart18: ChartData,
    rightCombinedChartHome: ChartData,
    rightCombinedChartDraw: ChartData,
    rightCombinedChartAway: ChartData,
    isLoading: boolean
  }>>(new Map())

  // Actions

  /** 获取相似比赛 */
  async function fetchSimilarMatches(condition: Football.SimilarMatchesCondition) {
    isLoadingSimilarMatches.value = true
    try {
      const response = await getSimilarMatchesApi(condition)
      
      if (response.code === 0 && response.data) {
        // 后端直接返回数组，不是嵌套对象
        similarMatches.value = Array.isArray(response.data) ? response.data : []
        similarMatchesPagination.value = response.pagination || {
          current_page: 1,
          page_size: 20,
          total: 0,
          total_pages: 0
        }
        similarMatchesStatistics.value = response.statistics || null
      } else {
        console.error("获取相似比赛失败:", response.message)
        similarMatches.value = []
        similarMatchesPagination.value = {
          current_page: 1,
          page_size: 20,
          total: 0,
          total_pages: 0
        }
        similarMatchesStatistics.value = null
      }
    } catch (error) {
      console.error("Failed to fetch similar matches:", error)
      similarMatches.value = []
      similarMatchesPagination.value = {
        current_page: 1,
        page_size: 20,
        total: 0,
        total_pages: 0
      }
      similarMatchesStatistics.value = null
    } finally {
      isLoadingSimilarMatches.value = false
    }
  }

  /** 获取相似比赛的信号数据 */
  async function selectSimilarMatch(match: Football.SimilarMatches) {
    if (!match.fid) {
      console.error("比赛ID为空")
      return
    }

    const fid = match.fid
    
    // 如果已经存在该比赛的数据，直接返回
    if (similarMatchDataMap.value.has(fid)) {
      selectedSimilarMatch.value = match
      return
    }

    // 创建新的比赛数据记录
    const newMatchData = {
      signals293: [] as Football.Signal[],
      signals18: [] as Football.Signal[],
      leftTableData: [] as OddsData[],
      rightTableData: [] as OddsData[],
      leftBottomChart293: { xData: [], seriesData: [] } as ChartData,
      leftBottomChart18: { xData: [], seriesData: [] } as ChartData,
      rightCombinedChartHome: { xData: [], seriesData: [] } as ChartData,
      rightCombinedChartDraw: { xData: [], seriesData: [] } as ChartData,
      rightCombinedChartAway: { xData: [], seriesData: [] } as ChartData,
      isLoading: true
    }
    
    similarMatchDataMap.value.set(fid, newMatchData)
    selectedSimilarMatch.value = match
    console.log("当前选择的相似比赛:", match)

    try {
      const [company293Response, company18Response] = await Promise.all([
        getMatcheSignalApi({ fid, company_id: 293 }),
        getMatcheSignalApi({ fid, company_id: 18 })
      ])

      if (company293Response.code === 0 && company293Response.data) {
        newMatchData.signals293 = company293Response.data
        processSimilarMatchCompanyData(company293Response.data, true, fid)
      } else {
        console.error("获取威廉希尔数据失败:", company293Response.message)
      }

      if (company18Response.code === 0 && company18Response.data) {
        newMatchData.signals18 = company18Response.data
        processSimilarMatchCompanyData(company18Response.data, false, fid)
      } else {
        console.error("获取必发数据失败:", company18Response.message)
      }

      generateSimilarMatchCombinedChartData(fid)

    } catch (error) {
      console.error("Failed to fetch similar match signal data:", error)
      similarMatchDataMap.value.delete(fid)
    } finally {
      newMatchData.isLoading = false
    }
  }

  /** 处理相似比赛的公司数据 */
  function processSimilarMatchCompanyData(signals: Football.Signal[], isCompany293: boolean = true, fid?: number): void {
    const sortedSignals = [...signals].sort((a, b) => {
      if (!a.odds_time || !b.odds_time) return 0
      return new Date(a.odds_time).getTime() - new Date(b.odds_time).getTime()
    })

    // 处理表格数据
    const tableData = sortedSignals.map((signal: Football.Signal) => ({
      oddsTime: signal.odds_time,
      homeWin: signal.home_odds,
      draw: signal.draw_odds,
      awayWin: signal.away_odds,
      homeWinRate: `${(signal.prob_home_odds * 100).toFixed(2)}%`,
      drawRate: `${(signal.prob_draw_odds * 100).toFixed(2)}%`,
      awayWinRate: `${(signal.prob_away_odds * 100).toFixed(2)}%`,
      signalHome: toFixedFour(signal.signal_home),
      signalDraw: toFixedFour(signal.signal_draw),
      signalAway: toFixedFour(signal.signal_away)
    }))

    // 处理图表数据
    const chartData = generateCompanyChartData(signals, isCompany293 ? "威廉希尔" : "必发")

    // 如果指定了fid，则更新对应比赛的数据，否则更新全局数据
    if (fid !== undefined && similarMatchDataMap.value.has(fid)) {
      const matchData = similarMatchDataMap.value.get(fid)!
      if (isCompany293) {
        matchData.leftTableData = tableData
        matchData.leftBottomChart293 = chartData
      } else {
        matchData.rightTableData = tableData
        matchData.leftBottomChart18 = chartData
      }
    } else {
      // 保持向后兼容
      if (isCompany293) {
        similarMatchLeftTableData.value = tableData
        similarMatchLeftBottomChart293.value = chartData
      } else {
        similarMatchRightTableData.value = tableData
        similarMatchLeftBottomChart18.value = chartData
      }
    }

    console.log(`相似比赛${isCompany293 ? "威廉希尔" : "必发"}数据处理完成`)
  }

  /** 生成相似比赛的组合图表数据 */
  function generateSimilarMatchCombinedChartData(fid?: number): void {
    console.log("开始处理相似比赛组合图表数据")
    
    // 如果指定了fid，则生成对应比赛的图表数据
    if (fid !== undefined && similarMatchDataMap.value.has(fid)) {
      const matchData = similarMatchDataMap.value.get(fid)!
      
      // 如果两个公司都没有数据，清空图表
      if (matchData.signals293.length === 0 && matchData.signals18.length === 0) {
        console.warn("相似比赛两个公司都没有数据")
        matchData.rightCombinedChartHome = { xData: [], seriesData: [] }
        matchData.rightCombinedChartDraw = { xData: [], seriesData: [] }
        matchData.rightCombinedChartAway = { xData: [], seriesData: [] }
        return
      }

      // 获取两个公司的时间范围
      const timeRange293 = getTimeRange(matchData.signals293)
      const timeRange18 = getTimeRange(matchData.signals18)
      
      let timeRange: { start: string; end: string }
      
      if (timeRange293 && timeRange18) {
        // 合并时间范围
        const start = new Date(Math.min(new Date(timeRange293.start).getTime(), new Date(timeRange18.start).getTime()))
        const end = new Date(Math.max(new Date(timeRange293.end).getTime(), new Date(timeRange18.end).getTime()))
        timeRange = {
          start: start.toISOString().replace('T', ' ').substring(0, 19),
          end: end.toISOString().replace('T', ' ').substring(0, 19)
        }
      } else {
        timeRange = timeRange293 || timeRange18!
      }

      // 生成每小时null的时间序列
      const timePoints = generateHourlyNullSeries(timeRange.start, timeRange.end)
      
      // 合并两个公司的数据
      const home293Data = mergeDataWithNullSeries(matchData.signals293, timePoints, 'signal_home')
      const home18Data = mergeDataWithNullSeries(matchData.signals18, timePoints, 'signal_home')
      const draw293Data = mergeDataWithNullSeries(matchData.signals293, timePoints, 'signal_draw')
      const draw18Data = mergeDataWithNullSeries(matchData.signals18, timePoints, 'signal_draw')
      const away293Data = mergeDataWithNullSeries(matchData.signals293, timePoints, 'signal_away')
      const away18Data = mergeDataWithNullSeries(matchData.signals18, timePoints, 'signal_away')

      // 生成图表数据
      matchData.rightCombinedChartHome = {
        xData: timePoints,
        seriesData: [
          { name: "威廉希尔-主队信号", data: home293Data },
          { name: "必发-主队信号", data: home18Data }
        ]
      }

      matchData.rightCombinedChartDraw = {
        xData: timePoints,
        seriesData: [
          { name: "威廉希尔-平局信号", data: draw293Data },
          { name: "必发-平局信号", data: draw18Data }
        ]
      }

      matchData.rightCombinedChartAway = {
        xData: timePoints,
        seriesData: [
          { name: "威廉希尔-客队信号", data: away293Data },
          { name: "必发-客队信号", data: away18Data }
        ]
      }

      console.log("相似比赛右侧组合图表数据生成完成")
    } else {
      // 保持向后兼容
      console.log("开始处理相似比赛组合图表数据")
      
      // 如果两个公司都没有数据，清空图表
      if (similarMatch293Signals.value.length === 0 && similarMatch18Signals.value.length === 0) {
        console.warn("相似比赛两个公司都没有数据")
        resetSimilarMatchCombinedCharts()
        return
      }

      // 获取两个公司的时间范围
      const timeRange293 = getTimeRange(similarMatch293Signals.value)
      const timeRange18 = getTimeRange(similarMatch18Signals.value)
      
      let timeRange: { start: string; end: string }
      
      if (timeRange293 && timeRange18) {
        // 合并时间范围
        const start = new Date(Math.min(new Date(timeRange293.start).getTime(), new Date(timeRange18.start).getTime()))
        const end = new Date(Math.max(new Date(timeRange293.end).getTime(), new Date(timeRange18.end).getTime()))
        timeRange = {
          start: start.toISOString().replace('T', ' ').substring(0, 19),
          end: end.toISOString().replace('T', ' ').substring(0, 19)
        }
      } else {
        timeRange = timeRange293 || timeRange18!
      }

      // 生成每小时null的时间序列
      const timePoints = generateHourlyNullSeries(timeRange.start, timeRange.end)
      
      // 合并两个公司的数据
      const home293Data = mergeDataWithNullSeries(similarMatch293Signals.value, timePoints, 'signal_home')
      const home18Data = mergeDataWithNullSeries(similarMatch18Signals.value, timePoints, 'signal_home')
      const draw293Data = mergeDataWithNullSeries(similarMatch293Signals.value, timePoints, 'signal_draw')
      const draw18Data = mergeDataWithNullSeries(similarMatch18Signals.value, timePoints, 'signal_draw')
      const away293Data = mergeDataWithNullSeries(similarMatch293Signals.value, timePoints, 'signal_away')
      const away18Data = mergeDataWithNullSeries(similarMatch18Signals.value, timePoints, 'signal_away')

      // 生成图表数据
      similarMatchRightCombinedChartHome.value = {
        xData: timePoints,
        seriesData: [
          { name: "威廉希尔-主队信号", data: home293Data },
          { name: "必发-主队信号", data: home18Data }
        ]
      }

      similarMatchRightCombinedChartDraw.value = {
        xData: timePoints,
        seriesData: [
          { name: "威廉希尔-平局信号", data: draw293Data },
          { name: "必发-平局信号", data: draw18Data }
        ]
      }

      similarMatchRightCombinedChartAway.value = {
        xData: timePoints,
        seriesData: [
          { name: "威廉希尔-客队信号", data: away293Data },
          { name: "必发-客队信号", data: away18Data }
        ]
      }

      console.log("相似比赛右侧组合图表数据生成完成")
    }
  }

  /** 重置相似比赛组合图表数据 */
  function resetSimilarMatchCombinedCharts() {
    similarMatchRightCombinedChartHome.value = { xData: [], seriesData: [] }
    similarMatchRightCombinedChartDraw.value = { xData: [], seriesData: [] }
    similarMatchRightCombinedChartAway.value = { xData: [], seriesData: [] }
  }

  /** 重置相似比赛信号相关数据 */
  function resetSimilarMatchSignalData() {
    similarMatch293Signals.value = []
    similarMatch18Signals.value = []
    similarMatchLeftTableData.value = []
    similarMatchRightTableData.value = []
    similarMatchLeftBottomChart293.value = { xData: [], seriesData: [] }
    similarMatchLeftBottomChart18.value = { xData: [], seriesData: [] }
    resetSimilarMatchCombinedCharts()
  }

  /** 重置所有相似比赛数据 */
  function resetAllSimilarMatchData() {
    similarMatches.value = []
    similarMatchesPagination.value = {
      current_page: 1,
      page_size: 20,
      total: 0,
      total_pages: 0
    }
    similarMatchesStatistics.value = null
    selectedSimilarMatch.value = null
    similarMatchDataMap.value.clear()
    resetSimilarMatchSignalData()
  }

  return {
    // 状态
    isLoadingSimilarMatches,
    isLoadingSimilarMatchSignals,
    similarMatches,
    similarMatchesPagination,
    similarMatchesStatistics,
    selectedSimilarMatch,
    similarMatch293Signals,
    similarMatch18Signals,
    similarMatchLeftTableData,
    similarMatchRightTableData,
    similarMatchLeftBottomChart293,
    similarMatchLeftBottomChart18,
    similarMatchRightCombinedChartHome,
    similarMatchRightCombinedChartDraw,
    similarMatchRightCombinedChartAway,
    similarMatchDataMap,
    
    // 方法
    fetchSimilarMatches,
    selectSimilarMatch,
    processSimilarMatchCompanyData,
    generateSimilarMatchCombinedChartData,
    resetSimilarMatchCombinedCharts,
    resetSimilarMatchSignalData,
    resetAllSimilarMatchData
  }
})
